package com.ehome.emergency.controller.admin;

import com.ehome.emergency.common.ApiPath;
import com.ehome.emergency.entities.Account;
import com.ehome.emergency.service.IAccountService;
import com.ehome.emergency.common.Constant;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * BasicFramework
 *
 * @author: xiaolei
 * @date: 2016-02-01 13:08
 * @desc: 首页
 */
@Controller
@RequestMapping
public class IndexController extends BaseAdminController {
    private static final Logger LOG = LoggerFactory.getLogger(IndexController.class);

    @Resource
    private IAccountService accountService;

    @RequestMapping(value = ApiPath.ADMIN_INDEX)
    public String index(Model model, HttpServletRequest request) {
        LOG.info("已登录到主页面");
        String accountId = (request.getSession().getAttribute(Constant.ACCOUNT_ID) != null) ? request.getSession().getAttribute(Constant.ACCOUNT_ID).toString() : "";
        if (StringUtils.isNotBlank(accountId)) {
            try {
                Account account = accountService.findById(Account.class, Long.valueOf(accountId));
                account.setPassword(null);
                model.addAttribute("account", account);
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
        }
        return "admin/index";
    }

    /**
     * 登出
     */
    @RequestMapping(value = ApiPath.ADMIN_LOGOUT)
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute(Constant.TENANT_ID);
        request.getSession().removeAttribute(Constant.USER_NAME);
        request.getSession().removeAttribute(Constant.ACCOUNT_ID);
        request.getSession().removeAttribute(Constant.ACCOUNT);
        request.getSession().removeAttribute(Constant.LOGIN_RANDOM);
        return "redirect:/login";
    }
}
